<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base href="<%=basePath%>"/>
    <title>茶叶进销存系统 - 订单管理</title>
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-logo" onclick="toggleSidebar()">
            <span><i class="fas fa-leaf tea-icon"></i> 茶叶进销存系统</span>
        </div>

        <div class="sidebar-menu">
            <div
                    class="menu-item "
                    onclick="location.href='views/home.jsp'"
            >
                <i class="fas fa-home"></i>
                <span>系统首页</span>
            </div>
            <div class="menu-item" onclick="location.href='TeaServlet'">
                <i class="fas fa-coffee"></i>
                <span>茶叶管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CategoryServlet'">
                <i class="fas fa-tags"></i>
                <span>分类管理</span>
            </div>
            <div class="menu-item" onclick="location.href='WarehouseServlet'">
                <i class="fas fa-boxes"></i>
                <span>仓库管理</span>
            </div>
            <div class="menu-item active" onclick="location.href='OrderServlet'">
                <i class="fas fa-receipt"></i>
                <span>订单管理</span>
            </div>
            <div class="menu-item" onclick="location.href='LogisticsServlet'">
                <i class="fas fa-shipping-fast"></i>
                <span>物流管理</span>
            </div>
            <div class="menu-item" onclick="location.href='SupplierServlet'">
                <i class="fas fa-truck"></i>
                <span>供应商管理</span>
            </div>
            <div class="menu-item" onclick="location.href='<%=basePath%>purchase/list'">
                <i class="fas fa-truck"></i>
                <span>采购管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CustomerServlet'">
                <i class="fas fa-users"></i>
                <span>客户管理</span>
            </div>
            <div class="menu-item" onclick="location.href='AddressServlet'">
                <i class="fas fa-map-marker-alt"></i>
                <span>地址管理</span>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            <div class="navbar-left">
                <h3><i class="fas fa-receipt tea-icon"></i> 订单管理</h3>
            </div>
            <div class="navbar-right">
                <span><i class="fas fa-user tea-icon"></i> 欢迎，${ username}管理员</span>
                <a href="logout" class="el-link el-link--danger ml-10"><i class="fas fa-sign-out-alt"></i> 退出</a>
            </div>
        </div>

        <!-- 错误信息显示 -->
        <c:if test="${not empty error}">
            <div class="el-card fade-in" style="margin-bottom: 20px;">
                <div class="el-card__body">
                    <div style="color: var(--danger-color); padding: 10px; background-color: #fef0f0; border-radius: 4px; border: 1px solid #fde2e2;">
                        <i class="fas fa-exclamation-circle"></i> ${error}
                    </div>
                </div>
            </div>
        </c:if>

        <!-- 内容卡片 -->
        <div class="el-card fade-in">
            <div class="el-card__header">
                <span><i class="fas fa-list tea-icon"></i> 订单列表</span>
                <div>
                    <input type="text" value="${orderNo}" class="el-input__inner" placeholder="请输入订单号" id="orderNo" style="width: 150px;">
                    <input type="text" value="${customerName}" class="el-input__inner" placeholder="请输入客户名称" id="customerName" style="width: 150px; margin-left: 10px;">
                    <select class="el-input__inner" id="status" style="width: 120px; margin-left: 10px;">
                        <option value="">所有状态</option>
                        <option value="0" ${status == '0' ? 'selected' : ''}>待支付</option>
                        <option value="1" ${status == '1' ? 'selected' : ''}>已支付</option>
                        <option value="2" ${status == '2' ? 'selected' : ''}>已发货</option>
                        <option value="3" ${status == '3' ? 'selected' : ''}>已完成</option>
                        <option value="4" ${status == '4' ? 'selected' : ''}>已取消</option>
                    </select>
                    <button class="el-button el-button--primary" onclick="searchOrder()" style="margin-left: 10px;">
                        <i class="fas fa-search"></i> 搜索
                    </button>
                    <button class="el-button el-button--success" onclick="location.href='OrderServlet?action=toAdd'" style="margin-left: 10px;">
                        <i class="fas fa-plus"></i> 新增订单
                    </button>
                </div>
            </div>
            <div class="el-card__body">
                <table class="el-table">
                    <thead>
                    <tr>
                        <th>订单号</th>
                        <th>客户名称</th>
                        <th>订单金额</th>
                        <th>订单状态</th>
                        <th>支付时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <c:forEach items="${orderList}" var="order">
                        <tr>
                            <td class="cell">${order.order_no}</td>
                            <td class="cell">${order.customer_name}</td>
                            <td class="cell">¥<fmt:formatNumber value="${order.total_amount}" pattern="#,##0.00"/></td>
                            <td class="cell">
                                <c:choose>
                                    <c:when test="${order.status == 0}">
                                        <span class="el-tag el-tag--danger">待支付</span>
                                    </c:when>
                                    <c:when test="${order.status == 1}">
                                        <span class="el-tag el-tag--success">已支付</span>
                                    </c:when>
                                    <c:when test="${order.status == 2}">
                                        <span class="el-tag">已发货</span>
                                    </c:when>
                                    <c:when test="${order.status == 3}">
                                        <span class="el-tag el-tag--success">已完成</span>
                                    </c:when>
                                    <c:when test="${order.status == 4}">
                                        <span class="el-tag el-tag--danger">已取消</span>
                                    </c:when>
                                </c:choose>
                            </td>
                            <td class="cell">
                                <c:if test="${not empty order.payment_time}">
                                    <fmt:formatDate value="${order.payment_time}" pattern="yyyy-MM-dd HH:mm"/>
                                </c:if>
                            </td>
                            <td class="cell">
                                <div class="action-links">
                                    <a href="OrderServlet?action=findById&id=${order.order_id}" class="el-link el-link--primary">
                                        <i class="fas fa-eye"></i> 查看
                                    </a>
                                    <c:if test="${order.status == 0}">
                                        <a href="javascript:void(0)" onclick="updateStatus(${order.order_id}, 1)" class="el-link el-link--success">
                                            <i class="fas fa-check"></i> 支付
                                        </a>
                                    </c:if>
                                    <c:if test="${order.status == 1}">
                                        <a href="javascript:void(0)" onclick="shipOrder(${order.order_id})" class="el-link el-link--primary">
                                            <i class="fas fa-shipping-fast"></i> 发货
                                        </a>
                                    </c:if>
                                    <c:if test="${order.status == 2}">
                                        <a href="javascript:void(0)" onclick="updateStatus(${order.order_id}, 3)" class="el-link el-link--success">
                                            <i class="fas fa-check-circle"></i> 完成
                                        </a>
                                    </c:if>
                                    <c:if test="${order.status < 2}">
                                        <a href="javascript:void(0)" onclick="updateStatus(${order.order_id}, 4)" class="el-link el-link--danger">
                                            <i class="fas fa-times"></i> 取消
                                        </a>
                                    </c:if>
                                    <a href="javascript:void(0)" onclick="deleteOrder(${order.order_id})" class="el-link el-link--danger">
                                        <i class="fas fa-trash"></i> 删除
                                    </a>
                                </div>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>

                <div class="el-pagination mt-20">
                    <div style="display: flex; align-items: center; justify-content: space-between;">
                        <!-- 每页显示条数选择 (左侧) -->
                        <div style="display: flex; align-items: center;">
                            <span style="margin-right: 10px;">每页显示：</span>
                            <select class="el-input__inner" id="pageSizeSelect" style="width: 80px; height: 35px"
                                    onchange="changePageSize(this.value)">
                                <option value="5" ${param.pageSize == '5' ? 'selected' : ''}>5</option>
                                <option value="10" ${param.pageSize == '10' ? 'selected' : ''}>10</option>
                                <option value="20" ${param.pageSize == '20' ? 'selected' : ''}>20</option>
                                <option value="50" ${param.pageSize == '50' ? 'selected' : ''}>50</option>
                            </select>
                            <span style="margin-left: 10px;">条</span>
                        </div>

                        <!-- 分页导航 (右侧) -->
                        <ul style="display: flex; list-style: none; margin: 0; padding: 0;">
                            <!-- 第一页 -->
                            <c:if test="${page > 1}">
                                <li>
                                    <a href="OrderServlet?action=${param.action}&orderNo=${orderNo}&customerName=${customerName}&status=${status}&page=1&pageSize=${pageSize}"
                                       class="page-link" title="第一页">««</a>
                                </li>
                            </c:if>

                            <!-- 上一页 -->
                            <c:if test="${page > 1}">
                                <li>
                                    <a href="OrderServlet?action=${param.action}&orderNo=${orderNo}&customerName=${customerName}&status=${status}&page=${page-1}&pageSize=${pageSize}"
                                       class="page-link" title="上一页">&laquo;</a>
                                </li>
                            </c:if>

                            <!-- 页码 -->
                            <c:forEach begin="1" end="${totalPages}" var="i">
                                <c:if test="${i == 1 || i == totalPages || (i >= page-2 && i <= page+2)}">
                                    <li>
                                        <a href="OrderServlet?action=${param.action}&orderNo=${orderNo}&customerName=${customerName}&status=${status}&page=${i}&pageSize=${pageSize}"
                                           class="page-link ${i == page ? 'active' : ''}">${i}</a>
                                    </li>
                                </c:if>
                                <c:if test="${i == page-3 || i == page+3}">
                                    <li><span class="page-ellipsis">...</span></li>
                                </c:if>
                            </c:forEach>

                            <!-- 下一页 -->
                            <c:if test="${page < totalPages}">
                                <li>
                                    <a href="OrderServlet?action=${param.action}&orderNo=${orderNo}&customerName=${customerName}&status=${status}&page=${page+1}&pageSize=${pageSize}"
                                       class="page-link" title="下一页">&raquo;</a>
                                </li>
                            </c:if>

                            <!-- 最后一页 -->
                            <c:if test="${page < totalPages}">
                                <li>
                                    <a href="OrderServlet?action=${param.action}&orderNo=${orderNo}&customerName=${customerName}&status=${status}&page=${totalPages}&pageSize=${pageSize}"
                                       class="page-link" title="最后一页">»»</a>
                                </li>
                            </c:if>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function searchOrder() {
        const orderNo = document.getElementById('orderNo').value;
        const customerName = document.getElementById('customerName').value;
        const status = document.getElementById('status').value;
        let url = "OrderServlet?action=search";
        if (orderNo) url += "&orderNo=" + encodeURIComponent(orderNo);
        if (customerName) url += "&customerName=" + encodeURIComponent(customerName);
        if (status) url += "&status=" + encodeURIComponent(status);
        location.href = url;
    }

    function changePageSize(size) {
        const orderNo = document.getElementById('orderNo').value;
        const customerName = document.getElementById('customerName').value;
        const status = document.getElementById('status').value;
        let url = "OrderServlet?action=${param.action || 'search'}&pageSize=" + size + "&page=1";
        if (orderNo) url += "&orderNo=" + encodeURIComponent(orderNo);
        if (customerName) url += "&customerName=" + encodeURIComponent(customerName);
        if (status) url += "&status=" + encodeURIComponent(status);
        location.href = url;
    }

    function updateStatus(orderId, status) {
        const statusText = ['待支付', '已支付', '已发货', '已完成', '已取消'];
        if (confirm('确定要将订单状态更新为"' + statusText[status] + '"吗？')) {
            location.href = 'OrderServlet?action=updateStatus&id=' + orderId + '&status=' + status;
        }
    }

    function shipOrder(orderId) {
        // 跳转到发货页面
        location.href = 'LogisticsServlet?action=toShip&orderId=' + orderId;
    }

    function deleteOrder(id) {
        if (confirm('确定要删除这个订单吗？删除后不可恢复！')) {
            location.href = 'OrderServlet?action=deleteById&id=' + id;
        }
    }

    let isCollapsed = false;

    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        isCollapsed = !isCollapsed;
        sidebar.classList.toggle('collapsed', isCollapsed);
        localStorage.setItem('sidebarCollapsed', isCollapsed);
    }

    window.onload = function() {
        const savedState = localStorage.getItem('sidebarCollapsed') === 'true';
        if(savedState) {
            document.getElementById('sidebar').classList.add('collapsed');
            isCollapsed = true;
        }
        document.getElementById("pageSizeSelect").value = "${param.pageSize}" || "10";
    }
</script>
</body>
</html>
